using MediatR;
using Microsoft.AspNetCore.Mvc;
using TerritoryGame.Application.Commands;
using TerritoryGame.Application.Queries;

namespace TerritoryGame.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class GameController : ControllerBase
{
    private readonly IMediator _mediator;
    
    public GameController(IMediator mediator)
    {
        _mediator = mediator;
    }
    
    [HttpPost("rooms")]
    public async Task<ActionResult<CreateRoomResult>> CreateRoom([FromBody] CreateRoomCommand command)
    {
        var result = await _mediator.Send(command);
        return Ok(result);
    }
    
    [HttpPost("rooms/join")]
    public async Task<ActionResult<JoinRoomResult>> JoinRoom([FromBody] JoinRoomCommand command)
    {
        var result = await _mediator.Send(command);
        if (!result.Success)
        {
            return BadRequest(result);
        }
        return Ok(result);
    }
    
    [HttpGet("rooms/{roomId}")]
    public async Task<ActionResult<GetRoomResult>> GetRoom(Guid roomId)
    {
        var query = new GetRoomQuery { RoomId = roomId };
        var result = await _mediator.Send(query);
        if (!result.Success)
        {
            return NotFound(result);
        }
        return Ok(result);
    }
    
    [HttpGet("rooms")]
    public async Task<ActionResult<GetRoomsResult>> GetRooms()
    {
        var query = new GetRoomsQuery();
        var result = await _mediator.Send(query);
        if (!result.Success)
        {
            return BadRequest(result);
        }
        return Ok(result);
    }
    
    [HttpGet("games/{gameId}/state")]
    public async Task<ActionResult<GetGameStateResult>> GetGameState(Guid gameId)
    {
        var query = new GetGameStateQuery { GameId = gameId };
        var result = await _mediator.Send(query);
        if (!result.Success)
        {
            return NotFound(result);
        }
        return Ok(result);
    }
    
    [HttpGet("games/{gameId}/stats")]
    public async Task<ActionResult<GetGameStatsResult>> GetGameStats(Guid gameId)
    {
        var query = new GetGameStatsQuery { GameId = gameId };
        var result = await _mediator.Send(query);
        if (!result.Success)
        {
            return NotFound(result);
        }
        return Ok(result);
    }
    
    [HttpPost("paint")]
    public async Task<ActionResult<PaintActionResult>> Paint([FromBody] PaintActionCommand command)
    {
        var result = await _mediator.Send(command);
        if (!result.Success)
        {
            return BadRequest(result);
        }
        return Ok(result);
    }
}
